package cn.yjr.vector;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import cn.yjr.vector.database.DaoMaster;
import cn.yjr.vector.database.DaoSession;
import cn.yjr.vector.database.YJRMessage;
import cn.yjr.vector.database.YJRMessageDao;
import cn.yjr.vector.tools.AudioRecorder;
import cn.yjr.vector.tools.ChatMessage;
import cn.yjr.vector.tools.FileHelper;
import cn.yjr.vector.tools.ImageChatMessage;
import cn.yjr.vector.tools.SharedPreferencesHelper;
import cn.yjr.vector.tools.TextChatMessage;
import cn.yjr.vector.tools.VoiceChatMessage;
import cn.yjr.vector.tools.YJRHttpClient;
import cn.yjr.vectori.adapter.MessageListAdapter;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity; 
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

/**
 * @author vector
 *
 */
public class ChatActivity extends SherlockActivity implements OnRefreshListener,OnClickListener{
	
	LinearLayout speakLayout;
	PullToRefreshListView listView;
	public static Map<String,ArrayList<ChatMessage>> allMessages = new HashMap<String,ArrayList<ChatMessage>>();
	ArrayList<ChatMessage> message = new ArrayList<ChatMessage>();
	ChatMessage messageNow;
	MessageListAdapter messageListAdapter;
	ListView actualListView;
	LayoutInflater inflater;
	ActionBar actionBar;
	FileHelper fileHelper;
	private Dialog dialog;
	private AudioRecorder mr;
	private MediaPlayer mediaPlayer;
	View title_bar;
	String lastMessageId = "1";
	private Cursor cursor;
	private Thread recordThread;
	private DaoMaster daoMaster;
	private Handler mHandler;
	Long timestamp;
	private DaoSession daoSession;
	private PopupWindow popup;
	View popup_view, parent;
	String pic_path;
	String pic_name;
	int SCALE = 3;
	String patient_name;
	RelativeLayout send_voice_rl;
	TextView ready_send_tv, record_again_tv;
	private SQLiteDatabase db;
	private static int MAX_TIME = 60;    //最长录制时间，单位秒，0为无时间限制
	private static int MIX_TIME = 1;     //最短录制时间，单位秒，0为无时间限制，建议设为1
	
	private static int RECORD_NO = 0;  //不在录音
	private static int RECORD_ING = 1;   //正在录音
	private static int RECODE_ED = 2;   //完成录音
	
	private static int RECODE_STATE = 0;      //录音的状态
	
	private static float recodeTime=0.0f;    //录音的时间
	private static double voiceValue=0.0;    //麦克风获取的音量值
	RelativeLayout refuse_rl, accept_rl, toolbar_rl;
	LinearLayout toolbar_ll;
	private ImageView dialog_img;
	boolean playState = false;  //播放状态
	private YJRMessageDao messageDao;
	DaoMaster.DevOpenHelper helper;
	Context context;
	int grid_view_show = 0;
	String response;
	List<Map<String, Object>> items;
	SimpleAdapter adapter;
	JSONObject jsonInfo;
	SharedPreferencesHelper spHelper;
	EditText content_et;
	DisplayImageOptions options;
	JSONObject info, patient, doctor;
	TextView send_tv, voice_tv,name_tv;
	String content;
	private PopupWindow menuWindow = null;
	LinearLayout content_ll;
	public static String avatar;
	ImageView plus_imv,voice_imv,keybord_imv;
	GridView gv;
	String patient_id;
	String consultStatus;
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_talkmessage);
		//调用getActionBar必须在setContentView之后
		inflater = this.getLayoutInflater();
		actionBar = getSupportActionBar();
		context = this;
		this.fileHelper = new FileHelper(this.context);
		initDataBase();
		initGridView();
		initPopup();
		initHandler();
		Intent intent = this.getIntent();
		
		String tmp = intent.getStringExtra("patient");
		consultStatus = intent.getStringExtra("consultStatus");
		if(tmp!=null||tmp.length()==0){
			try {
				info = new JSONObject(tmp);
				patient = info.getJSONObject("patient");
				patient_id = patient.getString("id");
				avatar = patient.getString("avatar");
				patient_name = patient.getString("name");
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(!allMessages.containsKey(patient_id))
			allMessages.put(patient_id, new ArrayList<ChatMessage>());
		else
			message = allMessages.get(patient_id);
		
		this.spHelper = new SharedPreferencesHelper(this.context);
		lastMessageId = spHelper.getStringValue("last_msg_id","1");
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.me_jobinfo)
		.showImageForEmptyUri(R.drawable.me_appointment)
		.showImageOnFail(R.drawable.head)
		.cacheInMemory(true)
		.cacheOnDisc(true)
		.considerExifParams(true)
		.displayer(new RoundedBitmapDisplayer(100))//是否设置为圆角，弧度为多少  
		.bitmapConfig(Bitmap.Config.RGB_565)
		.build();
		initTitleBar();
		
		initComponent();
		receiveMessage();
	}
	void initDataBase(){
		this.helper = new DaoMaster.DevOpenHelper(context, "yijiaren-db", null);
	    this.db = this.helper.getWritableDatabase();
	    this.daoMaster = new DaoMaster(this.db);
	    this.daoSession = this.daoMaster.newSession();
	    this.messageDao = this.daoSession.getYJRMessageDao();
	}
	void initGridView(){
		items = new ArrayList<Map<String,Object>>();
		Map<String, Object> item = new HashMap<String, Object>(); 
        item.put("imageItem", R.drawable.chatroom_sendphoto2x);//添加图像资源的ID   
        item.put("textItem", "完成咨询");//按序号添加ItemText   
        items.add(item); 
        item = new HashMap<String, Object>(); 
        item.put("imageItem", R.drawable.chatroom_sendphoto2x);//添加图像资源的ID   
        item.put("textItem", "结束并退款");//按序号添加ItemText   
        items.add(item); 
        item = new HashMap<String, Object>(); 
        item.put("imageItem", R.drawable.chatroom_sendphoto2x);//添加图像资源的ID   
        item.put("textItem", "发送图片");//按序号添加ItemText   
        items.add(item);
        adapter = new SimpleAdapter(this,  
                items,  
                R.layout.grid_item,  
                new String[]{"imageItem", "textItem"},  
                new int[]{R.id.grid_imv, R.id.grid_tip});
	}
	
	private void initHandler(){
		mHandler = new Handler() {
    		public void handleMessage(Message msg) {
    			switch (msg.what) {
    			case 2:
    				
    				RequestParams params = new RequestParams(); 
    		        params.add("lastMessageId", lastMessageId);
    				YJRHttpClient.post(context,"/message/getMsg", params, new JsonHttpResponseHandler(){
    					 @Override  
    			            public void onSuccess(JSONObject data) {  
    			             	JSONObject msg_tmp;
    			             	String msg_type;
    			             	try {
    								if(data.getInt("result") == 1){
    									YJRHttpClient.setCookie(context); 
    									
    									JSONArray msgList = data.getJSONArray("response");
    									int len = msgList.length();
    									if(len>=1){
    										lastMessageId = msgList.getJSONObject(len-1).getString("id");
    							
	    									for(int i = 0; i < len; i++){
	    										msg_tmp = msgList.getJSONObject(i);
	    										msg_type = msg_tmp.getString("type");
	    										String id = msg_tmp.getString("id");
	    										String content = msg_tmp.getString("content");
	    										Long time = msg_tmp.getLong("time");
	    										String receiverId = msg_tmp.getString("receiverId");
	    										boolean viewed = msg_tmp.getBoolean("viewed");
	    										String senderId = msg_tmp.getString("senderId");
	    										String type = msg_tmp.getString("type");
	    										if(!allMessages.containsKey(senderId)){
	    											allMessages.put(senderId, new ArrayList<ChatMessage>());
	    										}
	    										
	    										if(msg_type.equals("A")){
	    											if(!content.endsWith(".amr")){
	    												continue;
	    											}
	    											String[] a = content.split("/");
	    											String name = a[3];
	    											loadVoice(senderId,content,name);
	    											//这里要考虑把语音下载到本地
	    											
	    											YJRMessage new_msg = new YJRMessage(null,id,
	    													senderId,
	    													receiverId,
	    													time,
	    													type,
	    													content,
	    													"n" + name,
	    													null,
	    													viewed);
	    											messageDao.insert(new_msg);
	    										}else if(msg_type.equals("T")){
	    											
	    											ChatMessage msg = null;
	    											msg = new TextChatMessage(senderId,0, getDate(), "patient");
	    											((TextChatMessage)msg).setMessage(content);
	    											//Log.v("liuyi", senderId + "  " +id + "  " + patient_id);
	    											allMessages.get(senderId).add(msg);
	    											if(senderId.equals(patient_id))
	    												message.add(msg);
	    											YJRMessage new_msg = new YJRMessage(null,id,
	    													senderId,
	    													receiverId,
	    													time,
	    													type,
	    													null,
	    													null,
	    													content,
	    													viewed);
	    											messageDao.insert(new_msg);
	    										}else if(msg_type.equals("I")){
	    											
	    											//图片 TODO
	    											String[] a = content.split("/");
	    											String name = a[3];
	    											loadImage(senderId,content,name);
	    											//这里要考虑把语音下载到本地
	    											
	    											YJRMessage new_msg = new YJRMessage(null,id,
	    													senderId,
	    													receiverId,
	    													time,
	    													type,
	    													content,
	    													fileHelper.appFilePath + "pic/n" + name,
	    													null,
	    													viewed);
	    											messageDao.insert(new_msg);
	    										}
	    									}
	    									//messageListAdapter.message = message;
	    									messageListAdapter.notifyDataSetChanged();
	    									spHelper.putString("last_msg_id", lastMessageId);
    									}
    									receiveMessage();
    								
    								}else{
    									Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
    								}
    							} catch (JSONException e) {
    								// TODO Auto-generated catch block
    								e.printStackTrace();
    							}
    			            }  
    				});
    				
    				break;
    			default:
    				break;
                }
              super.handleMessage(msg);
    		}
        };
	}
	private void initTitleBar(){
		ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,ActionBar.LayoutParams.WRAP_CONTENT,Gravity.CENTER);
		title_bar = inflater.inflate(R.layout.chat_action_bar, null);
		actionBar.setCustomView(title_bar,lp);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
	}
	private void initComponent(){
		
		
		refuse_rl = (RelativeLayout) findViewById(R.id.refuse_rl);
		refuse_rl.setOnClickListener(this);
		accept_rl = (RelativeLayout) findViewById(R.id.accept_rl);
		accept_rl.setOnClickListener(this);
		toolbar_rl = (RelativeLayout) findViewById(R.id.toolbar_rl);
		toolbar_ll = (LinearLayout) findViewById(R.id.toolbar_ll);
		if(consultStatus.equals("A")){
			toolbar_ll.setVisibility(View.VISIBLE);
			toolbar_rl.setVisibility(View.INVISIBLE);
		}
		name_tv = (TextView) title_bar.findViewById(R.id.name);
		name_tv.setText(patient_name);
		listView = (PullToRefreshListView) findViewById(R.id.chatting_history_lv);
		listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				// Do work to refresh the list here.
				//new GetDataTask().execute();
			}
		});
		
		
		// Add an end-of-list listener
		listView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

			@Override
			public void onLastItemVisible() {
				Toast.makeText(ChatActivity.this, "End of List!", Toast.LENGTH_SHORT).show();
			}
		});
		
		actualListView = listView.getRefreshableView();
		messageListAdapter = new MessageListAdapter(message,ChatActivity.this,imageLoader, options,fileHelper,patient_id);
		actualListView.setAdapter(messageListAdapter);
		parent = findViewById(R.id.container);
		content_et = (EditText) findViewById(R.id.content_et);
		content_ll = (LinearLayout) findViewById(R.id.content_ll);
		voice_imv = (ImageView) findViewById(R.id.voice_imv);
		plus_imv = (ImageView) findViewById(R.id.plus_imv);
		plus_imv.setOnClickListener(this);
		send_tv = (TextView) findViewById(R.id.send_tv);
		send_tv.setOnClickListener(this);
		gv = (GridView) findViewById(R.id.grid_gv);
		gv.setAdapter(adapter); 
		
		voice_tv = (TextView) findViewById(R.id.voice_tv);
		keybord_imv = (ImageView) findViewById(R.id.keybord_imv);
		
		voice_imv.setOnClickListener(this);
		keybord_imv.setOnClickListener(this);
		send_voice_rl = (RelativeLayout) popup_view.findViewById(R.id.send_voice_rl);
		send_voice_rl.setOnClickListener(this);
		
		record_again_tv = (TextView) popup_view.findViewById(R.id.record_again_tv);
		ready_send_tv = (TextView) popup_view.findViewById(R.id.ready_send_tv);
		
		record_again_tv.setOnClickListener(this);
		ready_send_tv.setOnClickListener(this);
		
		gv.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Log.v("weiyi",position +"");
				switch(position){
				case 2:
					ShowPickDialog();
					break;
				default:
					break;
				}
				
			}
			
		});

		content_et.setOnFocusChangeListener(new OnFocusChangeListener(){

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if(hasFocus){
					grid_view_show = 0;
					gv.setVisibility(View.GONE);
				}
			}
			
		});
		content_et.addTextChangedListener(new TextWatcher(){
	
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
	
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				if(s.length()==0){
					plus_imv.setVisibility(View.VISIBLE);
					send_tv.setVisibility(View.INVISIBLE);
				}else{
					plus_imv.setVisibility(View.INVISIBLE);
					send_tv.setVisibility(View.VISIBLE);
				}
			}
	
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		voice_tv.setOnTouchListener(new OnTouchListener(){

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				int action = event.getAction();

				switch (action) {
				case MotionEvent.ACTION_UP:
					voice_tv.setText("按住说话");
//					if (menuWindow != null)
//						menuWindow.dismiss();
					if (RECODE_STATE == RECORD_ING) {
						RECODE_STATE=RECODE_ED;
						if (dialog.isShowing()) {
							dialog.dismiss();
						}
						try {
								mr.stop();
								voiceValue = 0.0;
							} catch (IOException e) {
								e.printStackTrace();
							}
								
								if (recodeTime < MIX_TIME) {
									showWarnToast();
									voice_tv.setText("按住说话");
									RECODE_STATE=RECORD_NO;
								}else{
									voice_tv.setText("按住说话");
									messageNow = new VoiceChatMessage("-1",2, timestamp +"", "doctor",timestamp+".amr");
									openPopWindow();
								}
					}

					break;
				case MotionEvent.ACTION_DOWN:
					voice_tv.setText("松开结束");
//					ViewGroup root = (ViewGroup) findViewById(R.id.container);
//					View view = inflater.inflate(R.layout.audio_recorder_ring, null);
//					menuWindow = new PopupWindow(view, 250, 250);
//					view.findViewById(R.id.recorder_ring).setVisibility(View.VISIBLE);
//					menuWindow.showAtLocation(root, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
					// AudioRecorder recorder=new AudioRecorder();
					
					if (RECODE_STATE != RECORD_ING) {
						Date date = new Date();
						timestamp = date.getTime();
						
						mr = new AudioRecorder("" + timestamp);
						RECODE_STATE=RECORD_ING;
						showVoiceDialog();
						try {
							mr.start();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mythread();
					}

					break;

				}

				return true;
			}
			
		});
	}
	
	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.send_tv:
			content = content_et.getText().toString();
			send();
			break;
		case R.id.plus_imv:
			if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
			{ 	//关闭输入法 
				InputMethodManager imm = (InputMethodManager) getApplicationContext() .getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); 
	
			}
			grid_view_show = 1 - grid_view_show;
			if(grid_view_show == 1){
				gv.setVisibility(View.VISIBLE);
				
			}else{
				gv.setVisibility(View.GONE);
			}
			break;
		case R.id.voice_imv:
			voice_imv.setVisibility(View.INVISIBLE);
			keybord_imv.setVisibility(View.VISIBLE);
			voice_tv.setVisibility(View.VISIBLE);
			content_ll.setVisibility(View.INVISIBLE);
			if(gv.isShown()){
				grid_view_show = 0;
				gv.setVisibility(View.GONE);
			}
			if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
			{ 	//关闭输入法 
				InputMethodManager imm = (InputMethodManager) getApplicationContext() .getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); 
	
			}
			break;
		case R.id.keybord_imv:
			if(gv.isShown()){
				grid_view_show = 0;
				gv.setVisibility(View.GONE);
			}
			keybord_imv.setVisibility(View.INVISIBLE);
			voice_imv.setVisibility(View.VISIBLE);
			content_ll.setVisibility(View.VISIBLE);
			voice_tv.setVisibility(View.INVISIBLE);
			break;
		case R.id.send_again:
			popup.dismiss();
			break;
		case R.id.ready_send_tv:
			try {
				sendVoice();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case R.id.send_voice_rl:
			play_voice((VoiceChatMessage) messageNow);
			break;
		case R.id.refuse_rl:
			//怎么获取订单号啊
			refuse("1");
			break;
		case R.id.accept_rl:
			accept("1");
			break;
		default:
				break;
		}
		
	}
	
	//TODO
	public Intent getSupportParentActivityIntent (){
		//Intent intent = new Intent(ChatActivity.this, Test.class);
		return null;
	}
	
	public void receiveMessage(){
		Thread newThread;
		final Message msg = new Message();
		msg.what = 2 ;
		newThread = new Thread(new Runnable(){	
			@Override
			public void run() {
				
				
				
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mHandler.sendMessage(msg);
			}
		
		});
		newThread.start();
	}
	
	@SuppressLint("SimpleDateFormat")
	public String getDate() {
		SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		return sim.format(new Date());
	}


	@Override
	public void onRefresh(PullToRefreshBase refreshView) {
		// TODO Auto-generated method stub
		
	}
	
	private void send(){
		RequestParams params = new RequestParams(); 
		params.add("m.receiverId", patient_id);
        params.add("m.content", content);
        params.add("m.type", "T");
		YJRHttpClient.post(context,"/message/postMsg", params, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {
						if(jsonInfo.getInt("result") == 1){
							YJRHttpClient.setCookie(context);
							JSONObject msg_tmp = jsonInfo.getJSONObject("response");
							ChatMessage msg = null;
							msg = new TextChatMessage(msg_tmp.getString("senderId"),0, getDate(), "doctor");
							((TextChatMessage)msg).setMessage(content);
							content_et.setText("");
							
							message.add(msg);
							messageListAdapter.notifyDataSetChanged();
							
							
							YJRMessage new_msg = new YJRMessage(null,msg_tmp.getString("id"),
									msg_tmp.getString("senderId"),
									msg_tmp.getString("receiverId"),
									msg_tmp.getLong("time"),
									msg_tmp.getString("type"),
									null,
									null,
									msg_tmp.getString("content"),
									msg_tmp.getBoolean("viewed"));
							messageDao.insert(new_msg);
							/*
							 * {"response":{"content":"test","id":140015832946500003,"ids":"140015832946500003","receiverId":"139913233891100001","senderId":"139818475273000001","time":140015832946,"type":"T","viewed":false},"result":1,"info":"发送消息成功"}
							 */
							
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
			 
			 @Override  
		     public void onFinish() {  
		         // Completed the request (either success or failure)  
		     }  
		});
	
	}
	
	
	private void refuse(String consultId){
		RequestParams params = new RequestParams(); 
		params.add("consultId", consultId);
		YJRHttpClient.post(context,"/doctor/denyConsult", params, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {
						if(jsonInfo.getInt("result") == 1){
							YJRHttpClient.setCookie(context);
							
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
			 
			 @Override  
		     public void onFinish() {  
		         // Completed the request (either success or failure)  
		     }  
		});
	
	}
	
	private void accept(String consultId){
		RequestParams params = new RequestParams(); 
		params.add("consultId", consultId);
		YJRHttpClient.post(context,"/doctor/acceptConsult", params, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {
						if(jsonInfo.getInt("result") == 1){
							YJRHttpClient.setCookie(context);
							
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
			 
			 @Override  
		     public void onFinish() {  
		         // Completed the request (either success or failure)  
		     }  
		});
	
	}
	 private void ShowPickDialog() {  
	      new AlertDialog.Builder(this)  
	              .setTitle("")  
	              .setNegativeButton("相册", new DialogInterface.OnClickListener() {  
	                  public void onClick(DialogInterface dialog, int which) {  
	                      dialog.dismiss();  
	                      /**  
	                       * 刚开始，我自己也不知道ACTION_PICK是干嘛的，后来直接看Intent源码，  
	                       * 可以发现里面很多东西，Intent是个很强大的东西，大家一定仔细阅读下  
	                       */ 
	                      Intent intent = new Intent(Intent.ACTION_PICK, null);  
	                        
	                      /**  
	                       * 下面这句话，与其它方式写是一样的效果，如果：  
	                       * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);  
	                       * intent.setType(""image/*");设置数据类型  
	                       * 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"  
	                       * 这个地方小马有个疑问，希望高手解答下：就是这个数据URI与类型为什么要分两种形式来写呀？有什么区别？  
	                       */ 
	                      intent.setDataAndType(  
	                              MediaStore.Images.Media.EXTERNAL_CONTENT_URI,  
	                              "image/*");  
	                      startActivityForResult(intent, 1);  

	                  }  
	              })  
	              .setPositiveButton("拍照", new DialogInterface.OnClickListener() {  
	                  public void onClick(DialogInterface dialog, int whichButton) {  
	                      dialog.dismiss();  
	                      /**  
	                       * 下面这句还是老样子，调用快速拍照功能，至于为什么叫快速拍照，大家可以参考如下官方  
	                       * 文档，you_sdk_path/docs/guide/topics/media/camera.html  
	                       * 我刚看的时候因为太长就认真看，其实是错的，这个里面有用的太多了，所以大家不要认为  
	                       * 官方文档太长了就不看了，其实是错的，这个地方小马也错了，必须改正  
	                       */  
	                      Intent intent = new Intent(  
	                              MediaStore.ACTION_IMAGE_CAPTURE);
	                      pic_name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))+".jpg";
	                      Uri imageUri = Uri.fromFile(new File(fileHelper.appFilePath+"pic/",pic_name));
	                      intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
	                      //下面这句指定调用相机拍照后的照片存储的路径  
//	                      intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri  
//	                              .fromFile(new File(fileHelper.appFilePath + "pic/",  
//	                                      "head.jpeg")));  
	                      startActivityForResult(intent, 2);  
	                  }
	              }).show();  
	  }
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
	      switch (requestCode) {

	      // 如果是直接从相册获取  
	      case 1:
	    	  Uri originalUri = data.getData();
	    	  String[] proj = {MediaStore.Images.Media.DATA};
	    	  
	            //好像是android多媒体数据库的封装接口，具体的看Android文档
	            Cursor cursor = managedQuery(originalUri, proj, null, null, null); 
	            //按我个人理解 这个是获得用户选择的图片的索引值
	            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	            //将光标移至开头 ，这个很重要，不小心很容易引起越界
	            cursor.moveToFirst();
	            //最后根据索引值获取图片路径
	            String path = cursor.getString(column_index);
	            pic_path = path;
	            int last_index = path.lastIndexOf('/');
	            pic_name = path.substring(last_index + 1, path.length());
	            Log.v("liuyi", pic_name);
	            Log.v("liuyi",path);
	            try {
					sendPic(pic_path, pic_name);
					if(gv.isShown()){
						grid_view_show = 0;
						gv.setVisibility(View.GONE);
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

                     
	    	  
	          break;  
	      // 如果是调用相机拍照时  
	      case 2:  
	    	  if(resultCode == Activity.RESULT_OK&&null!=data){
	    		  
	    		pic_path = fileHelper.appFilePath+"pic/"+pic_name;
	    		 try {
	 				sendPic(pic_path, pic_name);
	 				if(gv.isShown()){
	 					grid_view_show = 0;
	 					gv.setVisibility(View.GONE);
	 				}
	 			} catch (FileNotFoundException e) {
	 				// TODO Auto-generated catch block
	 				e.printStackTrace();
	 			}
	    		
	    		/*    		  
		          Uri uri1 = data.getData();
		          if(uri1 == null){
		        	  Bundle bundle = data.getExtras();
		        	  if(bundle!=null){
		        		  Bitmap photo = (Bitmap) bundle.get("data");
		        	  }else{
		        		  Toast.makeText(context, "get the image from camera. error", Toast.LENGTH_SHORT).show(); 
		        	  }
		          }
		          */
	    	  }
	    	 
	          break;  
	      default:  
	          break;  

	      }  
	      super.onActivityResult(requestCode, resultCode, data);  
	  }  
	  
	  
	  
	  
	//录音时显示Dialog
		void showVoiceDialog(){
			dialog = new Dialog(context,R.style.DialogStyle);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
			dialog.setContentView(R.layout.my_dialog);
			dialog_img=(ImageView)dialog.findViewById(R.id.dialog_img);
			dialog.show();
		}
		
		//录音时间太短时Toast显示
		void showWarnToast(){
			Toast toast = new Toast(context);
			 LinearLayout linearLayout = new LinearLayout(context);
			 linearLayout.setOrientation(LinearLayout.VERTICAL); 
			 linearLayout.setPadding(20, 20, 20, 20);
			
			// 定义一个ImageView
			 ImageView imageView = new ImageView(context);
			 imageView.setImageResource(R.drawable.voice_to_short); // 图标
			 
			 TextView mTv = new TextView(context);
			 mTv.setText("时间太短   录音失败");
			 mTv.setTextSize(14);
			 mTv.setTextColor(Color.WHITE);//字体颜色
			 //mTv.setPadding(0, 10, 0, 0);
			 
			// 将ImageView和ToastView合并到Layout中
			 linearLayout.addView(imageView);
			 linearLayout.addView(mTv);
			 linearLayout.setGravity(Gravity.CENTER);//内容居中
			 linearLayout.setBackgroundResource(R.drawable.record_bg);//设置自定义toast的背景
			 
			 toast.setView(linearLayout); 
			 toast.setGravity(Gravity.CENTER, 0,0);//起点位置为中间     100为向下移100dp
			 toast.show();				
		}
		
		
		//录音线程
		private Runnable ImgThread = new Runnable() {

			@Override
			public void run() {
				recodeTime = 0.0f;
				while (RECODE_STATE==RECORD_ING) {
					if (recodeTime >= MAX_TIME && MAX_TIME != 0) {
						imgHandle.sendEmptyMessage(0);
					}else{
					try {
						Thread.sleep(200);
						recodeTime += 0.2;
						if (RECODE_STATE == RECORD_ING) {
							voiceValue = mr.getAmplitude();
							imgHandle.sendEmptyMessage(1);
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				}
			}

			Handler imgHandle = new Handler() {
				@Override
				public void handleMessage(Message msg) {
	            
					switch (msg.what) {
					case 0:
						//录音超过15秒自动停止
						if (RECODE_STATE == RECORD_ING) {
							RECODE_STATE=RECODE_ED;
							if (dialog.isShowing()) {
								dialog.dismiss();
							}
							try {
									mr.stop();
									voiceValue = 0.0;
								} catch (IOException e) {
									e.printStackTrace();
								}
									
									if (recodeTime < 1.0) {
										showWarnToast();
										voice_tv.setText("按住说话");
										RECODE_STATE=RECORD_NO;
									}else{
//										 record.setText("录音完成!点击重新录音");
//										 luyin_txt.setText("录音时间："+((int)recodeTime));
//										 luyin_path.setText("文件路径："+getAmrPath());
										
										//录音结束 TODO
									}
						}
						break;
					case 1:
						setDialogImage();
						break;
					default:
						break;
					}
					
				}
			};
		};
		//录音Dialog图片随声音大小切换
		void setDialogImage(){
			if (voiceValue < 200.0) {
				dialog_img.setImageResource(R.drawable.record_animate_01);
			}else if (voiceValue > 200.0 && voiceValue < 400) {
				dialog_img.setImageResource(R.drawable.record_animate_02);
			}else if (voiceValue > 400.0 && voiceValue < 800) {
				dialog_img.setImageResource(R.drawable.record_animate_03);
			}else if (voiceValue > 800.0 && voiceValue < 1600) {
				dialog_img.setImageResource(R.drawable.record_animate_04);
			}else if (voiceValue > 1600.0 && voiceValue < 3200) {
				dialog_img.setImageResource(R.drawable.record_animate_05);
			}else if (voiceValue > 3200.0 && voiceValue < 5000) {
				dialog_img.setImageResource(R.drawable.record_animate_06);
			}else if (voiceValue > 5000.0 && voiceValue < 7000) {
				dialog_img.setImageResource(R.drawable.record_animate_07);
			}else if (voiceValue > 7000.0 && voiceValue < 10000.0) {
				dialog_img.setImageResource(R.drawable.record_animate_08);
			}else if (voiceValue > 10000.0 && voiceValue < 14000.0) {
				dialog_img.setImageResource(R.drawable.record_animate_09);
			}else if (voiceValue > 14000.0 && voiceValue < 17000.0) {
				dialog_img.setImageResource(R.drawable.record_animate_10);
			}else if (voiceValue > 17000.0 && voiceValue < 20000.0) {
				dialog_img.setImageResource(R.drawable.record_animate_11);
			}else if (voiceValue > 20000.0 && voiceValue < 24000.0) {
				dialog_img.setImageResource(R.drawable.record_animate_12);
			}else if (voiceValue > 24000.0 && voiceValue < 28000.0) {
				dialog_img.setImageResource(R.drawable.record_animate_13);
			}else if (voiceValue > 28000.0) {
				dialog_img.setImageResource(R.drawable.record_animate_14);
			}
		}
		
		
		//录音计时线程
		void mythread(){
			recordThread = new Thread(ImgThread);
			recordThread.start();
		}
		
		
		private void sendVoice() throws FileNotFoundException{
			RequestParams params = new RequestParams(); 
			File file = new File(fileHelper.appFilePath
	                + "voice/"+timestamp+".amr"); 
			params.add("fileFileName",timestamp+".amr");
			params.put("file", file);  
		    params.add("receiverId",patient_id);
		    params.add("type","A");
	        YJRHttpClient.post(context,"/message/postFileMsg", params, new JsonHttpResponseHandler(){
				 @Override  
		            public void onSuccess(JSONObject data) {
		             	jsonInfo = data;
		             	try {
							if(jsonInfo.getInt("result") == 1){
								YJRHttpClient.setCookie(context); 
								//Toast.makeText(context, "发送语音成功", Toast.LENGTH_LONG).show();
								JSONObject msg_tmp = jsonInfo.getJSONObject("response");
								String id = msg_tmp.getString("id");
								String content = msg_tmp.getString("content");
								Long time = msg_tmp.getLong("time");
								String receiverId = msg_tmp.getString("receiverId");
								boolean viewed = msg_tmp.getBoolean("viewed");
								String senderId = msg_tmp.getString("senderId");
								String type = msg_tmp.getString("type");
								
								
								ChatMessage msg = null;
								msg = new VoiceChatMessage(senderId,2, time+"", "doctor",timestamp+".amr");
								message.add(msg);
								messageListAdapter.notifyDataSetChanged();
								
								
								YJRMessage new_msg = new YJRMessage(null,id,
										senderId,
										receiverId,
										time,
										type,
										content,
										timestamp+".amr",
										null,
										viewed);
								messageDao.insert(new_msg);
								popup.dismiss();
								
							}else{
								Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
		            }  
			});
		}
		
		
		private void sendPic(final String picpath, String picname) throws FileNotFoundException{
			RequestParams params = new RequestParams(); 
			File file = new File(picpath); 
			params.add("fileFileName",picname);
		    params.put("file", file);  
		    params.add("receiverId",patient_id);
		    params.add("type","I");
	        YJRHttpClient.post(context,"/message/postFileMsg", params, new JsonHttpResponseHandler(){
				 @Override  
		            public void onSuccess(JSONObject data) {  
		             	jsonInfo = data;
		             	try {
							if(jsonInfo.getInt("result") == 1){
								Toast.makeText(context, "发送图片成功", Toast.LENGTH_SHORT).show();
								YJRHttpClient.setCookie(context);
								JSONObject msg_tmp = jsonInfo.getJSONObject("response");
								String id = msg_tmp.getString("id");
								String content = msg_tmp.getString("content");
								Long time = msg_tmp.getLong("time");
								String receiverId = msg_tmp.getString("receiverId");
								boolean viewed = msg_tmp.getBoolean("viewed");
								String senderId = msg_tmp.getString("senderId");
								String type = msg_tmp.getString("type");
								
								
								ChatMessage msg = null;
								msg = new ImageChatMessage(senderId,1, time+"", "doctor",picpath);
								message.add(msg);
								messageListAdapter.notifyDataSetChanged();
								
								
								YJRMessage new_msg = new YJRMessage(null,id,
										senderId,
										receiverId,
										time,
										type,
										content,
										picpath,
										null,
										viewed);
								messageDao.insert(new_msg);
								//Toast.makeText(context, "发送图片成功", Toast.LENGTH_LONG).show();
							}else{
								Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
		            }  
			});
		}
		
		
		private void initPopup() {
			popup_view = inflater.inflate(R.layout.popup_view, null);
			 /**初始化PopupWindow*/  
	        popup = new PopupWindow(popup_view,  
	                ViewGroup.LayoutParams.MATCH_PARENT,  
	                ViewGroup.LayoutParams.WRAP_CONTENT);  
	        popup.setFocusable(true);// 取得焦点  
	        popup.setBackgroundDrawable(new BitmapDrawable());  
	        /**设置PopupWindow弹出和退出时候的动画效果*/  
	        popup.setAnimationStyle(R.style.rank_animation);
			
		}
		public void openPopWindow() {  
	        /**设置PopupWindow弹出后的位置*/  
			popup.showAtLocation(parent, Gravity.BOTTOM, 0, 0);  
	    }  
		
		
		protected void play_voice(VoiceChatMessage tmp) {
			String file_name = tmp.getFilePath();
			if (!playState) {
				mediaPlayer = new MediaPlayer();
				try
				{

					mediaPlayer.setDataSource(fileHelper.appFilePath
			                + "voice/"+file_name);
					mediaPlayer.prepare();
					mediaPlayer.start();
					playState=true;
					//设置播放结束时监听
					mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
						
						@Override
						public void onCompletion(MediaPlayer mp) {
							if (playState) {
								playState=false;
							}
						}
					});
				}
				catch (IllegalArgumentException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (IllegalStateException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			}else {
				if (mediaPlayer.isPlaying()) {
					mediaPlayer.stop();
					playState=false;
				}else {
					playState=false;
				}
			}
		}
		
		private void loadVoice(final String senderId,final String content, final String file_name){
			//Toast.makeText(context, "/pics/images/" + content, Toast.LENGTH_SHORT).show();
			String[] allowedContentTypes = new String[] { "audio/amr","text/html;charset=UTF-8", "application/octet-stream" };
			YJRHttpClient.get(context, "/pics/images/" + content, new BinaryHttpResponseHandler(allowedContentTypes) {  
			    @Override  
			    public void onSuccess(byte[] fileData) {  
			        // Do something with the file  
			    	//Toast.makeText(context, "file down", Toast.LENGTH_SHORT).show();
			    	getFileFromBytes(fileData, fileHelper.appFilePath + "voice/n"+ file_name);
			    	ChatMessage msg = null;
					msg = new VoiceChatMessage(senderId,2, file_name, "patient","n" + file_name);
					allMessages.get(senderId).add(msg);
					if(senderId.equals(patient_id))
						message.add(msg);
					//messageListAdapter.message = message;
					messageListAdapter.notifyDataSetChanged();
			    }  
			});  
		}
		private void loadImage(final String senderId,final String content, final String file_name){
			//Toast.makeText(context, "/pics/images/" + content, Toast.LENGTH_SHORT).show();
			String[] allowedContentTypes = new String[] {"image/jpeg","image/jpg","image/png", "audio/amr","text/html;charset=UTF-8", "application/octet-stream" };
			YJRHttpClient.get(context, "/pics/images/" + content, new BinaryHttpResponseHandler(allowedContentTypes) {  
			    @Override  
			    public void onSuccess(byte[] fileData) {  
			        // Do something with the file  
			    	//Toast.makeText(context, "file down", Toast.LENGTH_SHORT).show();
			    	getFileFromBytes(fileData, fileHelper.appFilePath + "pic/n"+ file_name);
			    	ChatMessage msg = null;
					msg = new ImageChatMessage(senderId,1, file_name, "patient",fileHelper.appFilePath + "pic/n" + file_name);
					allMessages.get(senderId).add(msg);
					if(senderId.equals(patient_id))
						message.add(msg);
					//messageListAdapter.message = message;
					messageListAdapter.notifyDataSetChanged();
			    }  
			});  
		}
		void getFileFromBytes(byte[] b, String outputFile) { 
			//Toast.makeText(context, "file path: " + outputFile, Toast.LENGTH_SHORT).show();
	         OutputStream os;
			try {
				os = new FileOutputStream(outputFile);
				try {
					os.write(b);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
	         //int len = b.length;
	    }
		 public Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {

		        int w = bitmap.getWidth();

		        int h = bitmap.getHeight();

		        Matrix matrix = new Matrix();

		        float scaleWidth = ((float) width / w);

		        float scaleHeight = ((float) height / h);

		        matrix.postScale(scaleWidth, scaleHeight);// 利用矩阵进行缩放不会造成内存溢出

		        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);

		        return newbmp;

		    }
		 /**Save image to the SD card**/

	    public static void savePhotoToSDCard(String path, String photoName,

	            Bitmap photoBitmap) {

	        if (android.os.Environment.getExternalStorageState().equals(

	                android.os.Environment.MEDIA_MOUNTED)) {

	            File dir = new File(path);

	            if (!dir.exists()) {

	                dir.mkdirs();

	            }

	            File photoFile = new File(path, photoName); //在指定路径下创建文件

	            FileOutputStream fileOutputStream = null;

	            try {

	                fileOutputStream = new FileOutputStream(photoFile);

	                if (photoBitmap != null) {

	                    if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100,

	                            fileOutputStream)) {

	                        fileOutputStream.flush();

	                    }

	                }

	            } catch (FileNotFoundException e) {

	                photoFile.delete();

	                e.printStackTrace();

	            } catch (IOException e) {

	                photoFile.delete();

	                e.printStackTrace();

	            } finally {

	                try {

	                    fileOutputStream.close();

	                } catch (IOException e) {

	                    e.printStackTrace();

	                }

	            }

	        }

	    }
}
